'use client';

import { useState, useEffect } from 'react';
import { Category, DEFAULT_CATEGORIES, STORAGE_KEYS } from '@/types';

interface CategoryManagerProps {
  onSelectCategory: (categoryId: string | null) => void;
  selectedCategory: string | null;
  className?: string;
}

export default function CategoryManager({ 
  onSelectCategory, 
  selectedCategory,
  className = '' 
}: CategoryManagerProps) {
  const [categories, setCategories] = useState<Category[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showAddForm, setShowAddForm] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState('');
  const [newCategoryColor, setNewCategoryColor] = useState('#6b7280');
  const [isEditing, setIsEditing] = useState<string | null>(null);
  const [editName, setEditName] = useState('');
  const [editColor, setEditColor] = useState('');

  // 加载分类
  useEffect(() => {
    const loadCategories = () => {
      setIsLoading(true);
      
      try {
        // 从localStorage获取分类
        const savedCategories = localStorage.getItem(STORAGE_KEYS.CATEGORIES);
        
        if (savedCategories) {
          setCategories(JSON.parse(savedCategories));
        } else {
          // 如果没有保存的分类，使用默认分类
          setCategories(DEFAULT_CATEGORIES);
          localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(DEFAULT_CATEGORIES));
        }
      } catch (error) {
        console.error('加载分类失败:', error);
        setCategories(DEFAULT_CATEGORIES);
      } finally {
        setIsLoading(false);
      }
    };
    
    loadCategories();
  }, []);

  // 添加新分类
  const addCategory = () => {
    if (!newCategoryName.trim()) return;
    
    const newId = `category_${Date.now()}`;
    const newCategory: Category = {
      id: newId,
      name: newCategoryName.trim(),
      color: newCategoryColor
    };
    
    const updatedCategories = [...categories, newCategory];
    setCategories(updatedCategories);
    localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(updatedCategories));
    
    // 重置表单
    setNewCategoryName('');
    setNewCategoryColor('#6b7280');
    setShowAddForm(false);
  };

  // 更新分类
  const updateCategory = (id: string) => {
    if (!editName.trim() || !isEditing) return;
    
    const updatedCategories = categories.map(cat => 
      cat.id === id ? { ...cat, name: editName.trim(), color: editColor } : cat
    );
    
    setCategories(updatedCategories);
    localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(updatedCategories));
    
    // 重置编辑状态
    setIsEditing(null);
    setEditName('');
    setEditColor('');
  };

  // 删除分类
  const deleteCategory = (id: string) => {
    // 确认删除
    if (!confirm('确定要删除此分类吗？该分类下的视频将变为未分类。')) return;
    
    const updatedCategories = categories.filter(cat => cat.id !== id);
    setCategories(updatedCategories);
    localStorage.setItem(STORAGE_KEYS.CATEGORIES, JSON.stringify(updatedCategories));
    
    // 如果删除的是当前选中的分类，重置选中状态
    if (selectedCategory === id) {
      onSelectCategory(null);
    }
  };

  // 开始编辑分类
  const startEditing = (category: Category) => {
    setIsEditing(category.id);
    setEditName(category.name);
    setEditColor(category.color);
  };

  // 取消编辑
  const cancelEditing = () => {
    setIsEditing(null);
    setEditName('');
    setEditColor('');
  };

  return (
    <div className={`mb-4 ${className}`}>
      <div className="flex items-center justify-between mb-2">
        <h3 className="text-sm font-medium text-gray-600 dark:text-gray-400">分类</h3>
        <button 
          onClick={() => setShowAddForm(!showAddForm)}
          className="text-xs text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
        >
          {showAddForm ? '取消' : '添加分类'}
        </button>
      </div>
      
      {/* 添加分类表单 */}
      {showAddForm && (
        <div className="mb-3 p-2 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700">
          <input
            type="text"
            placeholder="分类名称"
            value={newCategoryName}
            onChange={(e) => setNewCategoryName(e.target.value)}
            className="w-full mb-2 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-900"
            maxLength={10}
          />
          <div className="flex items-center mb-2">
            <span className="text-xs mr-2">颜色:</span>
            <input
              type="color"
              value={newCategoryColor}
              onChange={(e) => setNewCategoryColor(e.target.value)}
              className="w-8 h-6 border-0 p-0 bg-transparent"
            />
          </div>
          <button
            onClick={addCategory}
            disabled={!newCategoryName.trim()}
            className="w-full px-2 py-1 text-xs bg-blue-500 hover:bg-blue-600 disabled:bg-gray-400 text-white rounded"
          >
            添加
          </button>
        </div>
      )}
      
      {/* 分类列表 */}
      <div className="space-y-1">
        <button
          onClick={() => onSelectCategory(null)}
          className={`flex items-center w-full px-3 py-2 rounded text-sm ${
            selectedCategory === null 
              ? 'bg-gray-200 dark:bg-gray-700 font-medium' 
              : 'hover:bg-gray-100 dark:hover:bg-gray-800'
          }`}
        >
          <span className="flex-1 text-left">全部</span>
        </button>
        
        {isLoading ? (
          <div className="py-2 text-center text-xs text-gray-500">加载中...</div>
        ) : (
          categories.map(category => (
            <div key={category.id} className="relative group">
              {isEditing === category.id ? (
                <div className="p-2 bg-gray-50 dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-700">
                  <input
                    type="text"
                    value={editName}
                    onChange={(e) => setEditName(e.target.value)}
                    className="w-full mb-2 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-900"
                    maxLength={10}
                    autoFocus
                  />
                  <div className="flex items-center mb-2">
                    <span className="text-xs mr-2">颜色:</span>
                    <input
                      type="color"
                      value={editColor}
                      onChange={(e) => setEditColor(e.target.value)}
                      className="w-8 h-6 border-0 p-0 bg-transparent"
                    />
                  </div>
                  <div className="flex space-x-2">
                    <button
                      onClick={() => updateCategory(category.id)}
                      className="flex-1 px-2 py-1 text-xs bg-green-500 hover:bg-green-600 text-white rounded"
                    >
                      保存
                    </button>
                    <button
                      onClick={cancelEditing}
                      className="flex-1 px-2 py-1 text-xs bg-gray-500 hover:bg-gray-600 text-white rounded"
                    >
                      取消
                    </button>
                  </div>
                </div>
              ) : (
                <button
                  onClick={() => onSelectCategory(category.id)}
                  className={`flex items-center w-full px-3 py-2 rounded text-sm ${
                    selectedCategory === category.id 
                      ? 'bg-gray-200 dark:bg-gray-700 font-medium' 
                      : 'hover:bg-gray-100 dark:hover:bg-gray-800'
                  }`}
                >
                  <span 
                    className="w-3 h-3 rounded-full mr-2 flex-shrink-0" 
                    style={{ backgroundColor: category.color }}
                  />
                  <span className="flex-1 text-left">{category.name}</span>
                  <span className="text-xs text-gray-500">{category.count || 0}</span>
                  
                  <div className="absolute right-2 hidden group-hover:flex space-x-1">
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        startEditing(category);
                      }}
                      className="p-1 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300"
                      title="编辑"
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-3 h-3">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931z" />
                      </svg>
                    </button>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        deleteCategory(category.id);
                      }}
                      className="p-1 text-gray-500 hover:text-red-500"
                      title="删除"
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-3 h-3">
                        <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
                      </svg>
                    </button>
                  </div>
                </button>
              )}
            </div>
          ))
        )}
      </div>
    </div>
  );
} 